package com.hundredhealth.rose.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.hundredhealth.rose.R;
import com.hundredhealth.rose.adapter.BasePullUpRecyclerAdapter;
import com.hundredhealth.rose.adapter.RecyclerHolder;
import com.hundredhealth.rose.model.Device;
import com.hundredhealth.rose.widget.EmptyLayout;

import java.util.ArrayList;


public class SearchBLEActivity extends MainListActivity<Device> {

    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    private BroadcastReceiver broadcastReceiver = null;
    private IntentFilter intentFilter = null;
    private ArrayList<Device> devices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        viewDelegate.setBackgroundImage(R.drawable.bg3);
        viewDelegate.mEmptyLayout.dismiss();
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        uninitBroadcast();
    }

    @Override
    protected BasePullUpRecyclerAdapter<Device> getAdapter() {
        return new BasePullUpRecyclerAdapter<Device>(recyclerView, datas, R.layout.item_device) {
            @Override
            public void convert(RecyclerHolder holder, Device item, int position) {
                holder.setText(R.id.deviceNameView, item.getDisplayName());
            }
        };
    }

    @Override
    protected ArrayList<Device> parserInAsync(byte[] t) {
        return null;
    }

    @Override
    public void onItemClick(View view, Object data, int position) {
        BluetoothDevice device = ((BluetoothDevice) data);
        Toast.makeText(SearchBLEActivity.this, "正在连接中...", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress());
        SearchBLEActivity.this.setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    protected void bindEvenListener() {
        recyclerView = viewDelegate.get(R.id.recyclerView);
        adapter = getAdapter();
        bindEven();
        viewDelegate.setOnRefreshListener(this);
        adapter.setOnItemClickListener(this);
        doRequest();
    }

    @Override
    public void doRequest() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (null == adapter) {
            finish();
            return;
        }

        if (!adapter.isEnabled()) {
            if (adapter.enable()) {
                while (!adapter.isEnabled()) ;
            } else {
                finish();
                return;
            }
        }
        devices = new ArrayList<>();
        datas.clear();
        adapter.cancelDiscovery();
        adapter.startDiscovery();
    }

    private void initBroadcast() {
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    if (device == null)
                        return;
                    devices.add(new Device(device.getName(), device.getAddress()));
                    adapter.refresh(devices);
                    datas = devices;
                } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED
                        .equals(action)) {
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                        .equals(action)) {
                    if (viewDelegate != null) {
                        if (devices.size() == 0) {
                            viewDelegate.mEmptyLayout.setErrorType(EmptyLayout.NODATA);
                        } else {
                            adapter.refresh(devices);
                            datas = devices;
                        }
                        viewDelegate.setSwipeRefreshLoadedState();
                    }
                }

            }

        };
        intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    private void uninitBroadcast() {
        if (broadcastReceiver != null)
            unregisterReceiver(broadcastReceiver);
    }

    private void bindEven() {
        viewDelegate.mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRequest();
                viewDelegate.mEmptyLayout.dismiss();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //滚动到底部的监听
                    LinearLayoutManager layoutManager = viewDelegate.getLayoutManager();
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int pastItems = layoutManager.findFirstVisibleItemPosition();
                    if ((pastItems + visibleItemCount) >= totalItemCount) {
                        onBottom();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        recyclerView.setAdapter(adapter);
    }
}
